﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ECCIT.Utilities;

namespace Golf
{
    public partial class getdirectory : System.Web.UI.Page
    {
        private string sOrder
        {
            get { return (string)this.ViewState["sOrder"]; }
            set { this.ViewState.Add("sOrder", value); }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                pan1.Visible = Request.QueryString["op"] != null && Request.QueryString["op"] == "2012" ? true : false;
                InitDDL();
                this.filelist.DataBind();
            }
        }

        private void InitDDL()
        {
            string path = Server.MapPath("~");  //获取根目录的物理路径
            this.DDLPath.Items.Add(new ListItem().Text = "请选择上传路径！");   //添加默认选项
            this.DDLPath.Items.Add(new ListItem().Text = path);   //添加根目录
            TraversingCatalog(path);
        }
        public bool TraversingCatalog(string path) //遍历文件夹        
        {
            if (Directory.Exists(path) == false) { return false; }
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            try
            {
                int allNum = dirInfo.GetDirectories().Length + dirInfo.GetFiles("*.*").Length;
                if (allNum == 0) //没有任何文件夹和文件就建立"（空白）"节点并返回false            
                {
                    return false;
                }
                //循环文件夹(避免混乱,先循环文件夹)            
                foreach (DirectoryInfo folder in dirInfo.GetDirectories())
                {
                    ListItem item = new ListItem();
                    item.Text = folder.FullName;
                    this.DDLPath.Items.Add(item);
                    TraversingCatalog(path + "/" + folder.Name); //递归遍历其它文件夹           
                }

            }
            catch (Exception)
            {

            }
            return true;
        }


        /// <summary>
        /// 上传判断处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnUpload_Click(object sender, EventArgs e)
        {
            string uploadpath = txtPath.Text.Trim() + "\\";
            int maxfilesize = 2 * 1024 * 1024;    //上传的最大限制
            string temp_ext = file.FileName.Substring(file.FileName.LastIndexOf("."), file.FileName.Length - (file.FileName.LastIndexOf(".")));  //获取扩展名
            if (temp_ext == ".rar")
            {
                UnRar();
                return;
            }
            string file_name = file.FileName;     //获取文件名
            if (file.PostedFile.ContentLength != 0)      //判断选取对话框选取的文件长度是否为0
            {
                if (file.PostedFile.ContentLength > maxfilesize)
                {
                    Response.Write("<script>alert('上传文件超过最大限制!');</script>");
                    return;
                }
                try
                {
                    file.PostedFile.SaveAs(uploadpath + file_name);
                    Response.Write("<script>alert('上传成功!');</script>");
                }
                catch (Exception)
                {
                    Response.Write("<script>alert('上传失败！ 请输入有效的路径重新上传!  ');</script>");
                    return;
                }

            }
        }
        protected void DDLPath_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DDLPath.SelectedItem.Text != "请选择上传路径！")
            {
                this.txtPath.Text = DDLPath.SelectedItem.Text;   //将下拉框中选择的值赋给 路径文本框

                BindData();
            }
            else
                this.txtPath.Text = "";      //给文本框赋值为“”
        }

        private void BindData()
        {
            DirectoryInfo dirInfo = new DirectoryInfo(this.DDLPath.SelectedItem.Text.ToString().Trim());
            List<FileInfomation> list = new List<FileInfomation>();
            var fies = dirInfo.GetFiles();
            foreach (var v in dirInfo.GetFiles())
            {
                FileInfomation info = new FileInfomation();
                info.name = v.Name.ToString();
                info.updateTime = v.LastWriteTime.ToString();
                info.createTime = v.CreationTime.ToString();
                info.type = v.GetType().ToString();
                info.size = v.Length.ToString() + "KB";
                list.Add(info);
            }
            var strorder = string.IsNullOrEmpty(sOrder) ? "name DESC" : sOrder;
            this.filelist.DataSource = list.OrderBy(strorder);
            this.filelist.DataBind();

        }

        private void UnRar()
        {
            string savePath = this.txtPath.Text.Trim();
            string name = file.FileName.ToString();
            file.SaveAs(savePath + name);    //解压前的文件
            //解压rar
            Process Process1 = new Process();
            Process1.StartInfo.FileName = savePath + name;    //压缩文件名
            Process1.Start();//解压开始 
            while (!Process1.HasExited)           //等待解压的完成 
            {

            }
            File.Delete(savePath + name);//删除rar文件 
            Response.Write("<script>alert('上传压缩成功');</script>");
        }

        protected void btndownload_Click(object sender, EventArgs e)
        {
            string filename = (sender as Button).CommandArgument.ToString();
            string fullname = Path.Combine(this.DDLPath.SelectedItem.Text, filename);
            try
            {
                File.Delete(fullname);
                BindData();
            }
            catch (Exception ex)
            {
                Response.Write(string.Format("<script>alert('Error occurred. Message:{0}');</script>", ex.Message));
            }
            ////下载
            //string filename = (sender as Button).CommandArgument.ToString();
            //string fullname = this.DDLPath.SelectedItem.Text + filename;
            //Response.Redirect("FileDownloadHandler.ashx?filePath=" + StringUtil.ToBase64String(fullname, Encoding.UTF8));
        }
        protected void filelist_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string filename = ((FileInfomation)e.Row.DataItem).name;
                string fullname = Path.Combine(this.DDLPath.SelectedItem.Text, filename);
                ((HyperLink)e.Row.FindControl("hlDownload")).NavigateUrl = "FileDownloadHandler.ashx?filePath=" + StringUtil.ToBase64String(fullname, Encoding.UTF8);
            }
        }
        protected void filelist_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

        }

        protected void hlDelete_Click(object sender, GridViewDeleteEventArgs e)
        {

        }

        #region 公用的排序方法 2012-5-22 李学明
        public const string ARROW_UP = "<font style='FONT-SIZE: 12pt; COLOR: White; FONT-FAMILY: Webdings'>5</font>";
        public const string ARROW_DOWN = "<font style='FONT-SIZE: 12pt; COLOR: White; FONT-FAMILY: Webdings'>6</font>";
        /// <summary>
        /// GridView排序方法
        /// </summary>
        /// <param name="gv"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string GetSortInfo(GridView gv, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression;
            string sortDirection = string.Empty;
            foreach (DataControlField column in gv.Columns)
            {
                if (column.GetType() == typeof(BoundField))
                {
                    ((BoundField)(column)).HtmlEncode = false;
                }
                if (column.SortExpression == e.SortExpression)
                {
                    string str = column.HeaderText;
                    if (str.IndexOf(ARROW_UP) + str.IndexOf(ARROW_DOWN) == -2)
                    {
                        column.HeaderText = column.HeaderText +ARROW_DOWN;
                        sortDirection = " DESC";
                    }
                    else if (str.IndexOf(ARROW_UP) != -1)
                    {
                        column.HeaderText = column.HeaderText.Replace(ARROW_UP,ARROW_DOWN);
                        sortDirection = " DESC";
                    }
                    else if (str.IndexOf(ARROW_DOWN) != -1)
                    {
                        column.HeaderText = column.HeaderText.Replace(ARROW_DOWN,ARROW_UP);
                        sortDirection = " ASC";
                    }
                }
                else
                {
                    column.HeaderText = column.HeaderText.Replace(ARROW_UP, "").Replace(ARROW_DOWN, "").Trim();
                }
            }
            return sortExpression + sortDirection;
        }

        #endregion
        protected void filelist_Sorting(object sender, GridViewSortEventArgs e)
        {
            this.sOrder = GetSortInfo(this.filelist, e);
            BindData();
        }
    }

    #region 公用的内存排序 2012-5-22 李学明
    public static class OrderByHelper
    {
        public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> enumerable, string orderBy)
        {
            return enumerable.AsQueryable().OrderBy(orderBy).AsEnumerable();
        }

        public static IQueryable<T> OrderBy<T>(this IQueryable<T> collection, string orderBy)
        {
            foreach (OrderByInfo orderByInfo in ParseOrderBy(orderBy))
                collection = ApplyOrderBy<T>(collection, orderByInfo);

            return collection;
        }

        private static IQueryable<T> ApplyOrderBy<T>(IQueryable<T> collection, OrderByInfo orderByInfo)
        {
            string[] props = orderByInfo.PropertyName.Split('.');
            Type type = typeof(T);

            ParameterExpression arg = Expression.Parameter(type, "x");
            Expression expr = arg;
            foreach (string prop in props)
            {
                // use reflection (not ComponentModel) to mirror LINQ
                PropertyInfo pi = type.GetProperty(prop);
                expr = Expression.Property(expr, pi);
                type = pi.PropertyType;
            }
            Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
            LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
            string methodName = String.Empty;

            if (!orderByInfo.Initial && collection is IOrderedQueryable<T>)
            {
                if (orderByInfo.Direction == SortDirection.Ascending)
                    methodName = "ThenBy";
                else
                    methodName = "ThenByDescending";
            }
            else
            {
                if (orderByInfo.Direction == SortDirection.Ascending)
                    methodName = "OrderBy";
                else
                    methodName = "OrderByDescending";
            }

            //TODO: apply caching to the generic methodsinfos?
            return (IOrderedQueryable<T>)typeof(Queryable).GetMethods().Single(
                method => method.Name == methodName
                        && method.IsGenericMethodDefinition
                        && method.GetGenericArguments().Length == 2
                        && method.GetParameters().Length == 2)
                .MakeGenericMethod(typeof(T), type)
                .Invoke(null, new object[] { collection, lambda });

        }

        private static IEnumerable<OrderByInfo> ParseOrderBy(string orderBy)
        {
            if (String.IsNullOrEmpty(orderBy))
                yield break;

            string[] items = orderBy.Split(',');
            bool initial = true;
            foreach (string item in items)
            {
                string[] pair = item.Trim().Split(' ');

                if (pair.Length > 2)
                    throw new ArgumentException(String.Format("Invalid OrderBy string '{0}'. Order By Format: Property, Property2 ASC, Property2 DESC", item));

                string prop = pair[0].Trim();

                if (String.IsNullOrEmpty(prop))
                    throw new ArgumentException("Invalid Property. Order By Format: Property, Property2 ASC, Property2 DESC");

                SortDirection dir = SortDirection.Ascending;

                if (pair.Length == 2)
                    dir = ("desc".Equals(pair[1].Trim(), StringComparison.OrdinalIgnoreCase) ? SortDirection.Descending : SortDirection.Ascending);

                yield return new OrderByInfo() { PropertyName = prop, Direction = dir, Initial = initial };

                initial = false;
            }

        }

        private class OrderByInfo
        {
            public string PropertyName { get; set; }
            public SortDirection Direction { get; set; }
            public bool Initial { get; set; }
        }

        private enum SortDirection
        {
            Ascending = 0,
            Descending = 1
        }
    }
    #endregion

    [Serializable]
    public class FileInfomation
    {
        public string name { get; set; }
        public string type { get; set; }
        public string createTime { get; set; }
        public string size { get; set; }
        public string updateTime { get; set; }
    }




}

